import { ElMessage } from "element-plus";
import { defineStore } from "pinia";
import {computed, ref} from 'vue'
import { useUserStore } from "./user";
import { insertCartAPI, findNewCartListAPI, delCartAPI} from "@/network/cart";
export const useCartStore = defineStore('cart', () => {
    const cartList = ref([])
    // 单独抽出更新购物车接口
   async function updateNewList() {
        const res = await findNewCartListAPI()
        // console.log(res);
        cartList.value = res.result
        // console.log(cartList.value);
    }
    // 1. 定义添加购物车方法
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token) // 响应式对象里的ref对象，不用.value
   async function addCart(goods) {
        const {skuId, count} = goods
        if (isLogin.value) {
            // 添加购物车接口
            // 用async写异步接口时，必须写await 不然会变成异步执行，跳过当前项代码，执行下一行
            await insertCartAPI({skuId, count}) 
            // 更新
            updateNewList()
            ElMessage({
                type: 'success',
                message: '成功加入购物车'
            })
            console.log('加入');
        } else {
             // 总是忘记写return 以至于找不到相同的skuId商品，后续判断老是走else
            const item = cartList.value.find((item) => {
                return goods.skuId === item.skuId
            })

            if (item) {
                item.count += goods.count
            } else {
                cartList.value.push(goods)
            }
            ElMessage({
                type: 'success',
                message: '成功加入购物车'
            })
        }
       
    }

    // 2. 定义删除商品方法
   async function delCart(skuId) {
        if (isLogin.value) {
           await delCartAPI([skuId])
            updateNewList()
            console.log('删除');
        } else {
            // console.log(skuId);
            //     // (1). 找到要删除的下标值
            //   const index = cartList.value.findIndex(item => {
            //         return skuId === item.skuId
            //     })
            //     console.log(index);
            //     cartList.value.splice(index, 1)
            // (2). 使用数组过滤方法 - filter 过滤掉删除的商品，重新赋值给cartList
            cartList.value = cartList.value.filter((item) => {
                return item.skuId !== skuId
        })
        }
        
    }
    // 退出登录删除购物车数据
    function clearCart() {
        cartList.value = []
    }

    // // 3. 计算头部购物车商品，定义计算属性
    // // (1) 总的数量
    const totalCount = computed(() => cartList.value.reduce((prev, current) => {
        return prev + current.count
    }, 0))
    
     // (2) 总价 所有count * price 之和
     const totalPrice = computed(() => {
        return cartList.value.reduce((prev, current) => {
            return prev + current.count * current.price
        }, 0)
     })
    //  console.log(totalPrice);

    // 4. 列表购物车单选函数
    function goodcheck(selected, skuId) {
        // console.log(selected, skuId);
       const item = cartList.value.find((item) => {
            return item.skuId === skuId
        })
        item.selected = selected
    }

    // 5. 单选决定全选
    const isAll = computed(() => {
        return cartList.value.every((item) => {
            return item.selected === true
        })
    })
    // 全选决定单选
    function allcheck(selected) {
        cartList.value.forEach((item) => {
            item.selected = selected
        })
    }

    // 6. 列表购物车，已选择数量、总价
    const selectedCount = computed(() => {
        return cartList.value.filter((item) => {
            return item.selected
        }).reduce((prev, current) => {
            return prev + current.count
        }, 0)
    })
    // 接口不完善，未选择的商品也会结算，所以选择用pinia的数据，筛选一下
    const checkoutCount = computed(() => {
        return cartList.value.filter((item) => {
            return item.selected
        })
    })
    
    
    // 总价
    const selectedPrice = computed(() => {
        return  cartList.value.filter((item) => {
            return item.selected
        }).reduce((prev, current) => {
            return prev + current.count * current.price
        }, 0)
    })
    // console.log(selectedPrice);
    return {
        cartList,
        addCart,
        delCart,
        totalCount,
        totalPrice,
        goodcheck,
        isAll,
        allcheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList,
        checkoutCount
    }
}, {
    persist: true
})